package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.Employee;
import cn.wolfcode.wms.domain.SystemMenu;
import cn.wolfcode.wms.mapper.SystemMenuMapper;
import cn.wolfcode.wms.service.ISystemMenuService;
import cn.wolfcode.wms.query.QueryForMenu;
import cn.wolfcode.wms.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
public class SystemMenuServiceImpl implements ISystemMenuService{

    @Autowired
    private SystemMenuMapper systemMenuMapper;

    public void saveOrUpdate(SystemMenu entity) {

        //判断是保存还是添加操作
        if (entity.getId() == null) {
            systemMenuMapper.insert(entity);
        }else{
            systemMenuMapper.updateByPrimaryKey(entity);
        }

    }

   public void delete(Long id) {

        //先删除子菜单在删除父菜单
       systemMenuMapper.deleteReltion(id);
        systemMenuMapper.deleteByPrimaryKey(id);
    }

    public SystemMenu get(Long id) {

        return systemMenuMapper.selectByPrimaryKey(id);
    }

    public List<SystemMenu> selectList() {

        return systemMenuMapper.selectAll();
    }

    public List<SystemMenu> query(QueryForMenu qo) {

        return systemMenuMapper.selectQueryMenu(qo);
    }

    public List<SystemMenu> getParentMenu(Long parentId) {

        //定义一个集合,存储父菜单
        List<SystemMenu> parents = new ArrayList<>();
        SystemMenu menu = systemMenuMapper.selectByPrimaryKey(parentId);
        while(menu != null){
            //把父菜单添加到集合中
            parents.add(menu);
            menu = menu.getParentMenu();
        }
        //逆序集合
        Collections.reverse(parents);

        return parents;
    }

    public List<Map<String,Object>> getSystemMenu(String menuSn) {

        //这里需要根据当前用户所拥有的菜单来决定用户能访问那些菜单
        //从session中取出当前用户的信息
        Employee user = UserContext.getCurrentUser();

        //判断当前用户是否是超级管理员
        if (!user.isAdmin()) {//不是超级管理员
            //那么就要查询出当前用户能访问的菜单(根据用户的id和sn去查询)
            List<Map<String, Object>> maps = systemMenuMapper.selectUserMenu(user.getId(), menuSn);
            return maps;
        }

        return systemMenuMapper.selectgetMenuSn(menuSn);
    }


}
